82. 删除排序链表中的重复元素 II
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3]
输出:[2,3]
答案
const head = {
'val':1,
'next':{
'val':2,
'next':{
'val':3,
'next':{
'val':3,
'next':{
'val':4,
'next':{
'val':4,
'next':{
'val':5,
'next':undefined
}
}
}
}
}
}
}
思路:
- 声明 ListNode 节点
- 防御性
- 注意 while 判断条件
cur.next && cur.next.next
- 下节点与下下节点的 val 对比
- 如果
cur.next .val === cur.next.next.val
递归查找相同的最后节点if (cur.next.val === cur.next.next.val) {
const x = cur.next.val
while (cur.next && cur.next.val === x) {
cur.next = cur.next.next
}
} - 如果不等
cur = cur.next
- 如果
// 1. 声明 ListNode 节点
class ListNode {
constructor(val, next) {
this.val = val
this.next = next || null
}
}
var deleteDuplicates = function (head) {
// 2. 防御性
if (!head) {
return head
}
const dummyNode = new ListNode(-1, head)
let cur = head
while (cur.next && cur.next.next) {
if (cur.next.val === cur.next.next.val) {
const x = cur.next.val
while (cur.next && cur.next.val === x) {
cur.next = cur.next.next
}
} else {
cur = cur.next
}
}
return dummyNode.next
}
console.log(deleteDuplicates(head))